import React, { useState, useRef, useEffect } from 'react'
import { getUserListApi, getRoleListApi, updateUserApi } from '../../services'
import type { UserItem } from '../../types/services'
import { PlusOutlined } from '@ant-design/icons'
import type { ActionType, ProFormInstance } from '@ant-design/pro-components'
import { ProTable, ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-components'
import { Button, message } from 'antd'
import CreateUserModal from './components/CreateUserModal'
import { getColumns } from './constant'

const Users: React.FC = () => {
  const actionRef = useRef<ActionType>()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editRowInfo, serEditRowInfo] = useState<UserItem | null>(null)
  const formRef = useRef<ProFormInstance>()
  const [modalVisible, setModalVisible] = useState<boolean>(false)

  const columns = getColumns({
    onClickRole: row => {
      serEditRowInfo(row)
      setModalVisible(true)
    },
    onClickEdit: row => {
      // message.success('编辑成功' + row.username)
      setIsModalOpen(true)
      serEditRowInfo(row)
    },
    onClickDel: row => {
      message.success('删除成功' + row.username)
    },
  })

  useEffect(() => {
    if (!isModalOpen) {
      serEditRowInfo(null)
    }
  }, [isModalOpen])


  return (
    <>
      <ProTable<UserItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        scroll={{ x: 1200 }}
        request={async (params) => {
          const { current, pageSize, ...other } = params
          const res = await getUserListApi({
            page: current!,
            pagesize: pageSize!,
            ...other
          })
          return {
            data: res.data.data.list,
            total: res.data.data.total,
            success: true
          }
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="_id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 5,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 20, 50],
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setIsModalOpen(true)
            }}
            type="primary"
          >
            新建
          </Button>
        ]}
      />
      <CreateUserModal
        visible={isModalOpen}
        setVisible={setIsModalOpen}
        editRowInfo={editRowInfo}
        refresh={() => actionRef.current?.reload()}
      />
      <ModalForm
        title="分配角色"
        formRef={formRef}
        open={modalVisible}
        onOpenChange={(visible) => {
          setModalVisible(visible)
          if (visible) {
            formRef.current?.setFieldsValue({
              role: editRowInfo?.role,
            })
          } else {
            formRef.current?.resetFields()
            serEditRowInfo(null)
          }
        }}
        onFinish={async (values) => {
          const res = await updateUserApi({
            id: editRowInfo!._id,
            ...values,
          })
          if (res.data.code === 200) {
            message.success('修改成功')
            setModalVisible(false)
            actionRef.current?.reload()
          } else {
            message.error(res.data.msg)
          }
        }}
      >
        <ProFormSelect
          width="md"
          name="role"
          placeholder="请选择角色"
          mode="multiple"
          request={async () => {
            const res = await getRoleListApi()
            console.log(res.data.data.list)
            return res.data.data.list.map(item => ({
              label: item.name,
              value: item.value,
            }))
          }}
          rules={[{ required: true, message: '请选择角色!' }]}
        />
      </ModalForm>
    </>
  );
};

export default Users